#!/usr/bin/python
#coding: utf-8

import sys
sys.path.append("..")

import pymysql
from Logging.ProxyLogging import log_Main
from Config.Config import conn, CreateKuaiIP

class ProxyObject(object):
    def __init__(self):
        self.conn = conn
        self.cur = self.conn.cursor()

        self.create_table = CreateKuaiIP
        self.insert_sql = "insert into kuaiIP(ip, port, type, url) values('%s', '%s', '%s', '%s');"

    def Create(self, ):
        u"创建数据库以及数据表"
        self.cur = self.conn.cursor()
        try:
            self.cur.execute("drop database if exists kuaidaili;")
            self.cur.execute("create database if not exists kuaidaili;")
            self.conn.select_db("kuaidaili")
            self.cur.execute(self.create_table)
            # log_Main("数据库以及数据表创建成功!!!", "info")
        except Exception as e:
            print e
        else:
            self.cur.close()

    def Insert(self, results):
        self.cur = self.conn.cursor()
        results = results
        # print len(results)
        while len(results):
            # 用完就会自动从set集合中移出
            res = results.pop()
            # 处理获取到的数据，提取出url
            ans = self.IPUrl(res)
            try:
                self.cur.execute(self.insert_sql % ans)
                self.conn.commit()
            except Exception as e:
                self.conn.rollback()
        self.cur.close()

    def IPUrl(self, res):
        if ',' in res[2]:
            s = res[2].split(",")[0].strip().lower() + "://" + res[0] + ":" + res[1]
        else :
            s = res[2].strip().lower() + "://" + res[0] + ":" + res[1]
        # print s
        return (res[0], res[1], res[2], s)

    def Close(self):
        # self.cur.close()
        # self.conn.close()
        pass